using UnityEditor;
using UnityEngine;
namespace HotUpdate.Editor {
    [CustomPropertyDrawer(typeof(TogglePropertyAttribute))]
    public class TogglePropertyAttributeDrawer : PropertyDrawer
    {
        private string m_CheckPath = null;
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if(CheckDisplay(property))
            {                
                EditorGUI.PropertyField(position, property, label, true);
            }
        }
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            if (CheckDisplay(property))
            {
                return EditorGUI.GetPropertyHeight(property, label);
            }
            else
            {
                return 0;
            }
        }

        bool CheckDisplay(SerializedProperty property)
        {
            TogglePropertyAttribute attr = attribute as TogglePropertyAttribute;
            if (attribute != null)
            {
                if(string.IsNullOrEmpty(m_CheckPath))
                {
                    var index = property.propertyPath.LastIndexOf(property.name);
                    m_CheckPath = $"{property.propertyPath.Remove(index)}{attr.CheckFieldName}";
                }                
                var cp = property.serializedObject.FindProperty(m_CheckPath);
                if(cp!=null)
                {
                    if(cp.type == "bool")
                    {
                        var display = cp.boolValue;
                        if(attr.Invert)
                        {
                            display = !display;
                        }
                        return display;
                    }                            
                    return true;
                }else
                {
                    return true;
                }                
            }
            else
            {
                return true;
            }
        }
    }

}

